package com.ljh.bigevent.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ljh.bigevent.mapper.ArticleMapper;
import com.ljh.bigevent.pojo.Article;
import com.ljh.bigevent.pojo.PageBean;
import com.ljh.bigevent.pojo.Result;
import com.ljh.bigevent.service.ArticleService;
import com.ljh.bigevent.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Resource
    ReentrantLock lock;

    @Override
    public Result addArticle(Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        article.setCreateUser((Integer) map.get("id"));
        add(article);
        return Result.success();
    }

    @Override
    public Result<PageBean<Article>> getArticleList(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        PageBean<Article> pb = list(pageNum, pageSize, categoryId, state);
        return Result.success(pb);
    }

    @Override
    public Result updateArticle(Article article) {
        lock.lock();
        article.setUpdateTime(LocalDateTime.now());
        update(article);
        lock.unlock();
        return Result.success();
    }

    @Override
    public Result<Article> getArticleById(Integer id) {
        Article ac = detail(id);
        return Result.success(ac);
    }

    @Override
    public Result deleteArticle(Integer id) {
        lock.lock();
        delete(id);
        lock.unlock();
        return Result.success();
    }

    @Override
    public void add(Article article) {
        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        PageBean<Article> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> as = articleMapper.list(userId, categoryId, state);
        PageInfo<Article> p = new PageInfo<>(as);
        pb.setTotal(p.getTotal());
        pb.setItems(p.getList());
        return pb;
    }

    @Override
    public void update(Article article) {
        articleMapper.update(article);
    }

    @Override
    public Article detail(Integer id) {
        return articleMapper.detail(id);
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }
}